<template>
    <div class="process-show">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2>工序管理</h2>
        </div>

        <!-- 操作栏 -->
        <div class="action-bar">
            <div class="left-actions">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button @click="handleExport" :disabled="selectedRows.length === 0">
                    <el-icon>
                        <Download />
                    </el-icon>
                    导出
                </el-button>
            </div>

            <div class="right-actions">
                <el-input v-model="searchForm.processName" placeholder="请搜索" class="search-input"
                    @keyup.enter="handleSearch">
                    <template #suffix>
                        <el-icon class="search-icon" @click="handleSearch">
                            <Search />
                        </el-icon>
                    </template>
                </el-input>

                <div class="layout-toggle">
                    <el-icon>
                        <Grid />
                    </el-icon>
                    <el-icon>
                        <List />
                    </el-icon>
                </div>
            </div>
        </div>

        <!-- 选择信息 -->
        <div v-if="selectedRows.length > 0" class="selection-info">
            <el-icon>
                <InfoFilled />
            </el-icon>
            <span>已选择 {{ selectedRows.length }} 项</span>
            <el-button type="text" @click="clearSelection">清除选择</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table ref="tableRef" :data="tableData" @selection-change="handleSelectionChange" v-loading="loading" stripe
            border>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="index" label="序号" width="80" />
            <el-table-column prop="processCode" label="工序编号" width="200" />
            <el-table-column prop="processName" label="工序名称" min-width="120" />
            <el-table-column prop="processClassificationName" label="工序分类" width="150" />
            <el-table-column prop="responsiblePerson" label="负责人" width="100" />
            <el-table-column prop="departmentName" label="所属部门" width="120" />
            <el-table-column prop="isEnabled" label="状态" width="80">
                <template #default="{ row }">
                    <el-tag :type="row.isEnabled ? 'success' : 'danger'">
                        {{ row.isEnabled ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="备注" min-width="150" />
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
                    <el-button type="text" @click="handleView(row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="left">
                <!-- 基础信息 -->
                <div class="form-section">
                    <div class="section-title">
                        <el-icon>
                            <Diamond />
                        </el-icon>
                        基础信息
                    </div>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="工序编码" prop="processCode">
                                <el-input v-model="form.processCode" placeholder="请输入工序编码"
                                    :disabled="form.isSystemCode" />
                                <el-checkbox v-model="form.isSystemCode" style="margin-left: 10px"
                                    @change="handleSystemCodeChange">
                                    系统编号
                                </el-checkbox>
                            </el-form-item>

                            <el-form-item label="工序分类" prop="processClassificationId">
                                <el-select v-model="form.processClassificationId" placeholder="请选择工序分类名称"
                                    style="width: 100%">
                                    <el-option v-for="item in processClassifications" :key="item.id"
                                        :label="item.classificationName" :value="item.id" />
                                </el-select>
                            </el-form-item>

                            <el-form-item label="所属部门" prop="departmentId">
                                <el-select v-model="form.departmentId" placeholder="请选择部门" style="width: 100%">
                                    <el-option v-for="item in departments" :key="item.id" :label="item.departmentName"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="工序名称" prop="processName">
                                <el-input v-model="form.processName" placeholder="请输入工序名称" />
                            </el-form-item>

                            <el-form-item label="负责人" prop="responsiblePerson">
                                <el-input v-model="form.responsiblePerson" placeholder="请选择负责人">
                                    <template #suffix>
                                        <el-icon>
                                            <User />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="状态">
                                <el-checkbox v-model="form.isEnabled">启用</el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="备注" prop="description">
                        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注" />
                    </el-form-item>
                </div>

                <!-- 附件 -->
                <div class="form-section">
                    <div class="section-title">
                        <el-icon>
                            <Paperclip />
                        </el-icon>
                        附件
                    </div>

                    <div class="attachment-container">
                        <div class="existing-attachments" v-if="form.attachments && form.attachments.length > 0">
                            <div v-for="(attachment, index) in form.attachments" :key="index" class="attachment-item">
                                <div class="attachment-info">
                                    <div class="file-name">{{ attachment.fileName }}</div>
                                    <div class="file-size">文件大小: {{ attachment.fileSize }}</div>
                                    <div class="upload-date">上传日期: {{ attachment.uploadDate }}</div>
                                </div>
                                <div class="attachment-actions">
                                    <el-button type="text" @click="handleViewAttachment(attachment)">查看</el-button>
                                    <el-button type="text" @click="handleDeleteAttachment(attachment)">删除</el-button>
                                </div>
                            </div>
                        </div>

                        <div class="upload-area">
                            <el-upload ref="uploadRef" :action="uploadUrl" :headers="uploadHeaders"
                                :on-success="handleUploadSuccess" :on-error="handleUploadError"
                                :before-upload="beforeUpload" :show-file-list="false" :multiple="true" :limit="10" drag
                                accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.zip,.rar">
                                <el-icon class="el-icon--upload">
                                    <UploadFilled />
                                </el-icon>
                                <div class="el-upload__text">
                                    <p>点击上传 / 拖拽文件到此区域</p>
                                    <p class="upload-tip">支持格式：图片、Word、Excel、PDF、CSV、压缩包等，单个文件最大50MB</p>
                                </div>
                            </el-upload>
                        </div>
                    </div>
                </div>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleDialogClose">关闭</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitting">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="工序详情" width="900px">
            <div class="detail-container">
                <div class="detail-header">
                    <h3>{{ detailData.processName }}</h3>
                    <div class="detail-meta">
                        <span>创建人: {{ detailData.createName }}</span>
                        <span>创建时间: {{ detailData.createTime }}</span>
                        <span v-if="detailData.updateName">最后修改人: {{ detailData.updateName }}</span>
                        <span v-if="detailData.updateTime">修改时间: {{ detailData.updateTime }}</span>
                    </div>
                </div>

                <div class="detail-actions">
                    <el-button type="primary" @click="handleEditFromDetail">编辑</el-button>
                    <el-button @click="handleDeleteFromDetail" style="color: #f56c6c">删除</el-button>
                    <el-button @click="handlePrint">打印</el-button>
                </div>

                <el-tabs v-model="activeTab">
                    <el-tab-pane label="工序信息" name="info">
                        <div class="detail-section">
                            <div class="section-title">
                                <el-icon>
                                    <Diamond />
                                </el-icon>
                                基础信息
                            </div>
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="工序编码">{{ detailData.processCode }}</el-descriptions-item>
                                <el-descriptions-item label="工序分类">{{ detailData.processClassificationName
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="负责人">{{ detailData.responsiblePerson
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="备注">{{ detailData.description || '-'
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="工序名称">{{ detailData.processName }}</el-descriptions-item>
                                <el-descriptions-item label="所属部门">{{ detailData.departmentName
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="状态">
                                    <el-tag :type="detailData.isEnabled ? 'success' : 'danger'">
                                        {{ detailData.isEnabled ? '启用' : '禁用' }}
                                    </el-tag>
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>

                        <div class="detail-section">
                            <div class="section-title">
                                <el-icon>
                                    <Paperclip />
                                </el-icon>
                                附件
                            </div>
                            <div class="attachment-list">
                                <div v-for="(attachment, index) in detailData.attachments" :key="index"
                                    class="attachment-card">
                                    <div class="attachment-content">
                                        <div class="file-name">{{ attachment.fileName }}</div>
                                        <div class="file-size">文件大小: {{ attachment.fileSize }}</div>
                                        <div class="upload-date">上传日期: {{ attachment.uploadDate }}</div>
                                    </div>
                                    <div class="attachment-actions">
                                        <el-button type="text" @click="handleViewAttachment(attachment)">查看</el-button>
                                        <el-button type="text"
                                            @click="handleDownloadAttachment(attachment)">下载</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="操作记录" name="log">
                        <div class="operation-log">
                            <p>操作记录功能待实现...</p>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Plus,
    Download,
    Search,
    Grid,
    List,
    InfoFilled,
    User,
    Paperclip,
    UploadFilled
} from '@element-plus/icons-vue'
import {
    ProcessShow,
    ProcessAdd,
    ProcessUpdate,
    ProcessDelete,
    GetProcessById,
    GetAllProcessClassifications,
    GetAllDepartments,
    ProcessExport,
    AddAttachments,
    GetAttachmentsByEntityId,
    DeleteAttachment
} from '@/Https/server'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const activeTab = ref('info')
const tableRef = ref()
const formRef = ref()
const uploadRef = ref()

const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])
const processClassifications = ref<any[]>([])
const departments = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
    processName: '',
})

// 分页
const pagination = reactive({
    pageIndex: 1,
    pageSize: 10,
    total: 0
})

// 表单数据
const form = reactive({
    id: 0,
    processCode: '',
    processName: '',
    processClassificationId: null as number | null,
    departmentId: null as number | null,
    responsiblePerson: '',
    description: '',
    sortOrder: 1,
    standardTime: 0,
    isEnabled: true,
    isSystemCode: false,
    attachments: [] as any[]
})

// 详情数据
const detailData = reactive({
    id: 0,
    processCode: '',
    processName: '',
    processClassificationId: 0,
    processClassificationName: '',
    departmentId: 0,
    departmentName: '',
    responsiblePerson: '',
    description: '',
    sortOrder: 1,
    standardTime: 0,
    isEnabled: true,
    createTime: '',
    createName: '',
    updateTime: '',
    updateName: '',
    attachments: [] as any[]
})

// 表单验证规则
const rules = {
    processCode: [
        { required: true, message: '请输入工序编码', trigger: 'blur' }
    ],
    processName: [
        { required: true, message: '请输入工序名称', trigger: 'blur' }
    ],
    processClassificationId: [
        { required: true, message: '请选择工序分类', trigger: 'change' }
    ],
    departmentId: [
        { required: true, message: '请选择所属部门', trigger: 'change' }
    ]
}

// 计算属性
const dialogTitle = computed(() => {
    return form.id > 0 ? '编辑工序' : '新增工序'
})

// 上传配置
const uploadUrl = `${import.meta.env.VITE_UploadAPP_API_URL}api/FileUpload/UploadFile` // 使用环境变量配置的上传地址
const uploadHeaders = {
    'Authorization': `Bearer ${localStorage.getItem('token')}`
    // 移除Content-Type，让浏览器自动设置正确的boundary
}

// 方法
const loadData = async () => {
    loading.value = true
    try {
        const params = {
            ...searchForm,
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize
        }

        const response: any = await ProcessShow(params)
        if (response.code === 200) {
            tableData.value = response.data.pageData.map((item: any, index: number) => ({
                ...item,
                index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1
            }))
            pagination.total = response.data.totalCount
        } else {
            ElMessage.error(response.message || '获取数据失败')
        }
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    } finally {
        loading.value = false
    }
}

const loadProcessClassifications = async () => {
    try {
        const response: any = await GetAllProcessClassifications()
        if (response.code === 200) {
            processClassifications.value = response.data
        }
    } catch (error) {
        console.error('加载工序分类失败:', error)
    }
}

const loadDepartments = async () => {
    try {
        const response: any = await GetAllDepartments()
        if (response.code === 200) {
            departments.value = response.data
        }
    } catch (error) {
        console.error('加载部门失败:', error)
    }
}

const handleSearch = () => {
    pagination.pageIndex = 1
    loadData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    loadData()
}

const handleCurrentChange = (page: number) => {
    pagination.pageIndex = page
    loadData()
}

const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
}

const clearSelection = () => {
    selectedRows.value = []
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
}

const resetForm = () => {
    Object.assign(form, {
        id: 0,
        processCode: '',
        processName: '',
        processClassificationId: null,
        departmentId: null,
        responsiblePerson: '',
        description: '',
        sortOrder: 1,
        standardTime: 0,
        isEnabled: true,
        isSystemCode: false,
        attachments: []
    })
}

const handleAdd = () => {
    resetForm()
    dialogVisible.value = true
}

const handleEdit = async (row: any) => {
    try {
        // 先加载工序详情
        const response: any = await GetProcessById({ id: row.id })
        if (response.code === 200) {
            Object.assign(form, {
                ...response.data,
                isSystemCode: false,
                attachments: [] // 先清空附件列表
            })

            // 加载附件列表
            try {
                const attachmentResponse: any = await GetAttachmentsByEntityId({
                    entityId: row.id,
                    entityType: 'Process'
                })
                if (attachmentResponse.code === 200) {
                    form.attachments = attachmentResponse.data.map((attachment: any) => ({
                        fileName: attachment.filename,
                        fileSize: formatFileSize(attachment.filesize),
                        uploadDate: new Date(attachment.uploadtime).toLocaleString(),
                        fileUrl: attachment.filepath,
                        filePath: attachment.filepath,
                        originalFileName: attachment.filename,
                        fileSizeBytes: attachment.filesize,
                        fileType: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
                        fileExtension: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
                        id: attachment.id // 添加附件ID，用于删除操作
                    }))
                }
            } catch (attachmentError) {
                console.error('加载附件失败:', attachmentError)
                form.attachments = []
            }

            dialogVisible.value = true
        } else {
            ElMessage.error(response.message || '获取工序详情失败')
        }
    } catch (error) {
        console.error('获取工序详情失败:', error)
        ElMessage.error('获取工序详情失败')
    }
}

const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除这个工序吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const response: any = await ProcessDelete({ Id: row.id })
        if (response.code === 200) {
            ElMessage.success('删除成功')
            loadData()
        } else {
            ElMessage.error(response.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

const handleView = async (row: any) => {
    try {
        const response: any = await GetProcessById({ id: row.id })
        if (response.code === 200) {
            Object.assign(detailData, response.data)

            // 加载附件列表
            try {
                const attachmentResponse: any = await GetAttachmentsByEntityId({
                    entityId: row.id,
                    entityType: 'Process'
                })
                if (attachmentResponse.code === 200) {
                    detailData.attachments = attachmentResponse.data.map((attachment: any) => ({
                        fileName: attachment.filename,
                        fileSize: formatFileSize(attachment.filesize),
                        uploadDate: new Date(attachment.uploadtime).toLocaleString(),
                        fileUrl: attachment.filepath,
                        filePath: attachment.filepath,
                        originalFileName: attachment.filename,
                        fileSizeBytes: attachment.filesize,
                        fileType: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
                        fileExtension: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
                        id: attachment.id // 添加附件ID，用于删除操作
                    }))
                }
            } catch (attachmentError) {
                console.error('加载附件失败:', attachmentError)
                detailData.attachments = []
            }

            detailDialogVisible.value = true
        } else {
            ElMessage.error(response.message || '获取详情失败')
        }
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

const handleExport = async () => {
    try {
        if (selectedRows.value.length === 0) {
            ElMessage.warning('请先选择要导出的数据')
            return
        }

        ElMessage.info('正在导出数据...')

        const exportData = {
            selectedIds: selectedRows.value.map(row => row.id),
            exportAll: false,
            processName: searchForm.processName || ''
        }

        const response: any = await ProcessExport(exportData)

        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `工序管理_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        const submitData = { ...form }
        let response: any

        if (submitData.id > 0) {
            response = await ProcessUpdate(submitData)
        } else {
            response = await ProcessAdd(submitData)
        }

        if (response.code === 200) {
            // 处理附件
            if (submitData.id === 0) {
                // 新增操作：如果有附件，则调用附件添加接口
                if (form.attachments && form.attachments.length > 0) {
                    try {
                        const attachmentDtos = form.attachments.map(attachment => ({
                            filename: attachment.fileName,
                            filepath: attachment.fileUrl,
                            filesize: attachment.fileSizeBytes,
                            entitytype: 'Process', // 业务类型为工序
                            entityid: response.data, // 使用返回的工序ID作为业务ID
                            createName: 'Admin' // 创建人，可以从用户上下文获取
                        }))

                        const attachmentResponse: any = await AddAttachments({
                            attachments: attachmentDtos
                        })

                        if (attachmentResponse.code === 200) {
                            ElMessage.success(`工序添加成功，并成功关联 ${attachmentResponse.data.length} 个附件`)
                        } else {
                            ElMessage.warning('工序添加成功，但附件关联失败')
                        }
                    } catch (attachmentError) {
                        console.error('附件关联失败:', attachmentError)
                        ElMessage.warning('工序添加成功，但附件关联失败')
                    }
                } else {
                    ElMessage.success('新增成功')
                }
            } else {
                // 编辑操作：附件删除已经在handleDeleteAttachment中处理，这里只需要处理新增的附件
                // 调试：输出当前附件状态
                console.log('保存时的附件状态:', form.attachments)
                console.log('附件详情:', form.attachments.map(att => ({
                    fileName: att.fileName,
                    id: att.id,
                    fileUrl: att.fileUrl
                })))

                // 检查是否有重复的附件
                const allFileNames = form.attachments.map(att => att.fileName)
                const duplicateFileNames = allFileNames.filter((fileName, index) => allFileNames.indexOf(fileName) !== index)
                if (duplicateFileNames.length > 0) {
                    console.error('发现重复附件:', duplicateFileNames)
                    console.error('重复附件详情:', form.attachments.filter(att => duplicateFileNames.includes(att.fileName)))
                }

                // 只处理真正的新附件（没有ID且有fileUrl的附件）
                const newAttachments = form.attachments.filter(attachment => !attachment.id && attachment.fileUrl)
                console.log('过滤后的新附件:', newAttachments)

                // 进一步检查：确保没有重复的文件名
                const uniqueNewAttachments = []
                const processedFileNames = new Set()

                // 使用已检测到的重复文件名
                console.log('检测到的重复文件名:', duplicateFileNames)

                for (const attachment of newAttachments) {
                    if (!processedFileNames.has(attachment.fileName)) {
                        uniqueNewAttachments.push(attachment)
                        processedFileNames.add(attachment.fileName)
                    } else {
                        console.warn(`跳过重复文件: ${attachment.fileName}`)
                    }
                }

                if (uniqueNewAttachments.length > 0) {
                    try {
                        const attachmentDtos = uniqueNewAttachments.map(attachment => ({
                            filename: attachment.fileName,
                            filepath: attachment.fileUrl,
                            filesize: attachment.fileSizeBytes,
                            entitytype: 'Process', // 业务类型为工序
                            entityid: submitData.id, // 使用当前工序ID作为业务ID
                            createName: 'Admin' // 创建人，可以从用户上下文获取
                        }))

                        const attachmentResponse: any = await AddAttachments({
                            attachments: attachmentDtos
                        })

                        if (attachmentResponse.code === 200) {
                            ElMessage.success(`工序修改成功，并成功关联 ${attachmentResponse.data.length} 个新附件`)
                        } else {
                            ElMessage.warning('工序修改成功，但新附件关联失败')
                        }
                    } catch (attachmentError) {
                        console.error('新附件关联失败:', attachmentError)
                        ElMessage.warning('工序修改成功，但新附件关联失败')
                    }
                } else {
                    ElMessage.success('修改成功')
                }
            }

            dialogVisible.value = false
            loadData()
        } else {
            ElMessage.error(response.message || '操作失败')
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
    } finally {
        submitting.value = false
    }
}

const handleDialogClose = () => {
    dialogVisible.value = false
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const handleEditFromDetail = () => {
    Object.assign(form, detailData)
    detailDialogVisible.value = false
    dialogVisible.value = true
}

const handleDeleteFromDetail = () => {
    handleDelete(detailData)
    detailDialogVisible.value = false
}

const handlePrint = () => {
    window.print()
}

const handleViewAttachment = (attachment: any) => {
    console.log(attachment);
    // 实现附件查看逻辑
    if (attachment.fileUrl) {
        // 对于图片和PDF文件，直接在新窗口中打开
        const fileExtension = attachment.fileExtension?.toLowerCase()
        if (['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.pdf'].includes(fileExtension)) {
            window.open(attachment.fileUrl, '_blank')
        } else {
            // 对于其他文件类型，提示下载
            ElMessage.info('此文件类型不支持在线预览，请下载后查看')
            handleDownloadAttachment(attachment)
        }
    } else {
        ElMessage.warning('文件链接不可用')
    }
}

const handleDownloadAttachment = (attachment: any) => {
    // 实现附件下载逻辑
    if (attachment.fileUrl) {
        // 创建一个隐藏的下载链接
        const link = document.createElement('a')
        link.href = attachment.fileUrl
        link.download = attachment.fileName || 'download'
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        ElMessage.success('开始下载文件')
    } else {
        ElMessage.warning('文件链接不可用')
    }
}

const handleDeleteAttachment = async (index: any) => {
    const attachment = index
    console.log(attachment)
    try {
        // 如果附件有ID，说明是已存在的附件，需要调用后端API删除
        if (attachment.id) {
            console.log('准备删除附件:', attachment)
            const response: any = await DeleteAttachment({ attachmentId: attachment.id })
            console.log('删除附件响应:', response)
            if (response.code === 200) {
                ElMessage.success('附件删除成功')
                // 从数组中移除
                form.attachments.splice(index, 1)
                console.log(`已删除附件: ${attachment.fileName}, ID: ${attachment.id}`)
            } else {
                ElMessage.error(response.message || '附件删除失败')
            }
        } else {
            // 如果是新上传的附件（还没有ID），直接从数组中移除
            form.attachments.splice(index, 1)
            ElMessage.success('附件已移除')
        }
    } catch (error) {
        console.error('删除附件失败:', error)
        ElMessage.error('删除附件失败')
    }
}

// 处理系统编号变化
const handleSystemCodeChange = (checked: boolean) => {
    if (checked) {
        // 生成系统编号
        generateSystemCode()
    } else {
        // 清空工序编码
        form.processCode = ''
    }
}

// 生成系统编号
const generateSystemCode = () => {
    // 获取当前时间戳
    const timestamp = Date.now()
    // 生成6位随机数
    const random = Math.floor(Math.random() * 900000) + 100000
    // 组合成编号：P + 时间戳后6位 + 随机数
    const systemCode = `P-${timestamp.toString().slice(-6)}-${random}`
    form.processCode = systemCode
}

const beforeUpload = (file: File) => {
    // 文件上传前的验证
    const supportedTypes = [
        // 图片类型
        'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp',
        // 文档类型
        'application/pdf',
        'application/msword', // .doc
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
        'application/vnd.ms-excel', // .xls
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
        'application/vnd.ms-powerpoint', // .ppt
        'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
        'text/plain', // .txt
        'text/csv', // .csv
        // 其他常用类型
        'application/zip', 'application/x-rar-compressed'
    ]

    // 更宽松的文件类型验证，主要检查文件扩展名
    const isValidType = supportedTypes.includes(file.type) ||
        file.name.toLowerCase().match(/\.(jpg|jpeg|png|gif|bmp|webp|pdf|doc|docx|xls|xlsx|ppt|pptx|txt|csv|zip|rar)$/)

    const isLt50M = file.size / 1024 / 1024 < 50 // 50MB

    if (!isValidType) {
        ElMessage.error('支持的文件格式：图片(JPG/PNG/GIF/BMP/WEBP)、文档(PDF/DOC/DOCX/XLS/XLSX/PPT/PPTX/TXT/CSV)、压缩包(ZIP/RAR)')
        return false
    }
    if (!isLt50M) {
        ElMessage.error('文件大小不能超过 50MB!')
        return false
    }

    console.log('文件验证通过:', file.name, file.type, file.size)
    return true
}

const handleUploadSuccess = (response: any, file: File) => {
    console.log('上传响应:', response)

    // 后端直接返回URL字符串，需要适配这种格式
    let fileUrl = ''
    if (typeof response === 'string') {
        fileUrl = response
    } else if (response.data) {
        fileUrl = response.data
    } else if (response.url) {
        fileUrl = response.url
    }

    if (fileUrl) {
        // 检查是否已经存在相同文件名的附件（更严格的检查）
        const existingAttachments = form.attachments.filter(att => att.fileName === file.name)
        if (existingAttachments.length > 0) {
            ElMessage.warning(`文件 "${file.name}" 已存在（${existingAttachments.length}个），请勿重复上传`)
            console.warn(`重复文件检查: ${file.name} 已存在 ${existingAttachments.length} 次`)
            console.log('现有附件列表:', form.attachments.map(att => ({ fileName: att.fileName, id: att.id })))
            return
        }

        const attachment = {
            fileName: file.name,
            fileSize: formatFileSize(file.size),
            uploadDate: new Date().toLocaleString(),
            fileUrl: fileUrl,
            filePath: fileUrl, // 使用URL作为路径
            originalFileName: file.name,
            fileSizeBytes: file.size,
            fileType: file.type,
            fileExtension: file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
        }

        form.attachments.push(attachment)
        ElMessage.success(`文件 "${file.name}" 上传成功`)
        console.log('附件已添加:', attachment)
    } else {
        ElMessage.error('上传响应格式错误')
        console.error('上传响应格式错误:', response)
    }
}

const handleUploadError = (error: any, file: File) => {
    console.error('上传失败:', error)
    ElMessage.error(`文件 "${file.name}" 上传失败: ${error.message || '网络错误'}`)
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'

    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}



// 生命周期
onMounted(() => {
    loadData()
    loadProcessClassifications()
    loadDepartments()
})
</script>

<style scoped>
.process-show {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    color: #303133;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-actions {
    display: flex;
    gap: 12px;
}

.right-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

.search-input {
    width: 300px;
}

.search-icon {
    cursor: pointer;
    color: #909399;
}

.search-icon:hover {
    color: #409eff;
}

.layout-toggle {
    display: flex;
    gap: 8px;
}

.layout-toggle .el-icon {
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    color: #909399;
}

.layout-toggle .el-icon:hover {
    background: #f5f7fa;
    color: #409eff;
}

.selection-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 6px;
    color: #409eff;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.form-section {
    margin-bottom: 24px;
}

.section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    font-weight: 600;
    color: #303133;
}

.attachment-container {
    display: flex;
    gap: 20px;
}

.existing-attachments {
    flex: 1;
}

.attachment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin-bottom: 12px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
}

.attachment-info {
    flex: 1;
}

.file-name {
    font-weight: 500;
    margin-bottom: 4px;
}

.file-size,
.upload-date {
    font-size: 12px;
    color: #6c757d;
}



.attachment-actions {
    display: flex;
    gap: 8px;
}

.attachment-actions .el-button {
    cursor: pointer;
    transition: all 0.3s ease;
}

.attachment-actions .el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-area {
    flex: 1;
}

.upload-area :deep(.el-upload-dragger) {
    width: 100%;
    height: 200px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    background: #fafafa;
    transition: all 0.3s ease;
}

.upload-area :deep(.el-upload-dragger:hover) {
    border-color: #409eff;
    background: #f0f9ff;
}

.upload-area :deep(.el-icon--upload) {
    font-size: 48px;
    color: #c0c4cc;
    margin-bottom: 16px;
}

.upload-area :deep(.el-upload__text) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
}

.upload-area :deep(.el-upload__text p) {
    margin: 4px 0;
}

.upload-tip {
    font-size: 12px !important;
    color: #909399 !important;
    margin-top: 8px !important;
}

.detail-container {
    padding: 20px;
}

.detail-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e9ecef;
}

.detail-header h3 {
    margin: 0 0 12px 0;
    color: #303133;
}

.detail-meta {
    display: flex;
    gap: 20px;
    font-size: 14px;
    color: #6c757d;
}

.detail-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
}

.detail-section {
    margin-bottom: 24px;
}

.attachment-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
}

.attachment-card {
    padding: 16px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
}

.attachment-content {
    margin-bottom: 12px;
}

.operation-log {
    padding: 40px;
    text-align: center;
    color: #6c757d;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>
